package com.baizhi.cmfz.controller;

import com.baizhi.cmfz.annotation.LogAnnotation;
import com.baizhi.cmfz.entity.Banner;
import com.baizhi.cmfz.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("banner")
public class BannerController {
    @Autowired
    private BannerService bannerService;

    @RequestMapping("add")
    @LogAnnotation(value = "添加轮播图", type = "insert")
    public boolean addBanner(Banner banner, HttpServletRequest request, MultipartFile file) {
        if (file != null) {
            //设置文件名
            String oldFileName = file.getOriginalFilename();
            String fileName = "/img/" + new Date().getTime() + "_" + oldFileName;
            //上传路径
            String path = request.getServletContext().getRealPath("/");
            //用流复制
            try {
                file.transferTo(new File(path + fileName));
                banner.setBannerImageUrl(fileName);
                bannerService.addBanner(banner);
                return true;
            } catch (IOException e) {
                return false;
            }
        } else {
            return bannerService.addBanner(banner) > 0;
        }
    }

    @RequestMapping("remove")
    @LogAnnotation(value = "删除轮播图", type = "delete")
    public boolean removeBanner(int[] ids) {
        return bannerService.removeBanner(ids) > 0;
    }

    @RequestMapping("update")
    @LogAnnotation(value = "更改轮播图信息", type = "update")
    public boolean updateBanner(Banner banner, HttpServletRequest request, MultipartFile file) {
        if (file != null) {
            //设置文件名
            String oldFileName = file.getOriginalFilename();
            String fileName = "/img/" + new Date().getTime() + "_" + oldFileName;
            //上传路径
            String path = request.getServletContext().getRealPath("/");
            //用流复制
            try {
                file.transferTo(new File(path + fileName));
                banner.setBannerImageUrl(fileName);
                bannerService.updateBanner(banner);
                return true;
            } catch (IOException e) {
                return false;
            }
        } else {
            return bannerService.updateBanner(banner) > 0;
        }
    }

    @RequestMapping("selectOne")
    @LogAnnotation(value = "根据id查找轮播图")
    public Banner selectOneBanner(int bannerId) {
        return bannerService.selectOneBanner(bannerId);
    }

    @RequestMapping("all")
    @LogAnnotation(value = "查找所有轮播图")
    public Map selectAllBanner(int page, int limit) {
        return bannerService.selectAllBanner(page, limit);
    }
}
